package cc.buttfu.thingbento;

import java.util.ArrayList;

import cc.buttfu.thingbento.R;

import android.accounts.NetworkErrorException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;

/**
 * @author dislink.now
 * 
 *         Screen to load and display scrolling list of shouts
 *         ("status updates").
 * 
 */
public class ShoutScreen extends Activity {

	/**
	 * Nag screen spinner
	 */
	private ProgressDialog dialog = null;

	PageLoader p = null;

	Thread shoutLoader;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onActivityResult(int, int,
	 * android.content.Intent)
	 * 
	 * If the user is not logged in, the LoginScreen activity is deployed. Upon
	 * obtaining of valid session cookie, it returns to this point and will
	 * retry the shout page loading process.
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		shoutLoader = new Thread(new Runnable() {

			@Override
			public void run() {
				retrieveShoutsLoop();
			}
		});
		shoutLoader.start();
	}

	private void retrieveShoutsLoop() {

		int delay = 3000;

		boolean cease = false;

		/*
		 * Ceases either when shouts are loaded and displayed, or when focus
		 * switches to login screen.
		 */
		while (!cease) {

			try {

				p = new ShoutLoader(this, "");
				cease = true;

			} catch (NetworkErrorException e) {
				/* TODO: handle network errors properly */
				e.printStackTrace();
			} catch (NotLoggedInException e) {

				runOnUiThread(new Runnable() {
					public void run() {
						Intent in = new Intent(ShoutScreen.this,
								LoginScreen.class);
						startActivityForResult(in, 0);
					}
				});
				cease = true;

			} catch (NagScreenException e) {
				runOnUiThread(new Runnable() {
					public void run() {
						if (dialog == null)
							dialog = ProgressDialog
									.show(
											ShoutScreen.this,
											"",
											"Consider taking out a paid subscription to thingbox",
											true);
					}
				});

				try {
					Thread.sleep(delay);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
				delay *= 2;
			}
			/*
			 * try { Thread.sleep(3000); } catch (InterruptedException e1) {
			 * e1.printStackTrace(); }
			 */
		}

		if (p != null && p.size() > 0) {
			runOnUiThread(new Runnable() {
				public void run() {

					/* Cancel nag-screen dialog */
					if (dialog != null)
						dialog.cancel();

					ArrayList<Post> posts = p.getPosts();

					/*
					 * The Adapter turns Post items into a form the ListView can
					 * display
					 */
					lv
							.setAdapter(new ShoutListAdapter(ShoutScreen.this,
									posts));
				}
			});
		}
	}

	ListView lv;

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.shoutscreenmenu, menu);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {

		/* The "Post" button */
		case R.id.postshoutmenuitem:
			runOnUiThread(new Runnable() {
				public void run() {
					Intent in = new Intent(ShoutScreen.this,
							PostShoutScreen.class);
					startActivityForResult(in, 0);
				}
			});

			return true;

			/* The "Logout" button */
		case R.id.logoutmenuitem:
			SharedPreferences prefs = PreferenceManager
					.getDefaultSharedPreferences(this);
			Editor ed = prefs.edit();
			ed.remove("cookie");
			ed.commit();

			/* TODO: make it clear the screen / return to previous activity */
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.shoutscreen);

		lv = (ListView) findViewById(R.id.shoutlist);

		/* This may take a while so don't run it on the UI thread */
		shoutLoader = new Thread(new Runnable() {

			@Override
			public void run() {
				retrieveShoutsLoop();
			}
		});
		shoutLoader.start();
	}

}